<template>
  <div class="manhole-covers-container">
	<el-row type="flex" justify="center" class="page-header" style="margin-bottom: 30px;">
	        <el-col :span="24" class="text-center">
	            <div class="title-wrapper">
	            <i class="el-icon-search el-icon--large"></i>
	            <h1 class="main-title">井盖监测管理系统</h1>
	            <p class="sub-title">实时监测每一块井盖状态，精准记录每一次异常反馈，用细致守护路面安全，让 “脚下隐患” 无处隐藏</p>
	            </div>
	        </el-col>
	    </el-row>
    <!-- 详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="井盖信息详情"
      width="70%"
      destroy-on-close
    >
      <el-descriptions title="井盖信息详情" direction="vertical" :column="4" :model="currentManholeCover" border>
        <el-descriptions-item label="井盖ID" :span="2">{{ currentManholeCover.coverId }}</el-descriptions-item>
        <el-descriptions-item label="位置ID" :span="2">{{ currentManholeCover.locationId }}</el-descriptions-item>
        <el-descriptions-item label="是否存在" :span="2">{{ currentManholeCover.coverExists ? '存在' : '不存在' }}</el-descriptions-item>
        <el-descriptions-item label="是否损坏" :span="2">{{ currentManholeCover.coverDamaged ? '损坏' : '未损坏' }}</el-descriptions-item>
        <el-descriptions-item label="状态" :span="4">{{ currentManholeCover.status }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>


    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑井盖信息"
      width="60%"
      destroy-on-close
    >
      <el-form 
        :model="editForm" 
        :rules="rules" 
        ref="editFormRef" 
        label-width="120px" 
        class="demo-ruleForm"
      >
        <el-form-item label="井盖ID" prop="coverId" disabled>
          <el-input v-model="editForm.coverId"></el-input>
        </el-form-item>
        <el-form-item label="位置ID" prop="locationId">
          <el-input v-model.number="editForm.locationId" type="number"></el-input>
        </el-form-item>
        <el-form-item label="是否存在" prop="coverExists">
          <el-radio-group v-model="editForm.coverExists">
            <el-radio :label="true">存在</el-radio>
            <el-radio :label="false">不存在</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否损坏" prop="coverDamaged">
          <el-radio-group v-model="editForm.coverDamaged">
            <el-radio :label="true">损坏</el-radio>
            <el-radio :label="false">未损坏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择状态">
            <el-option label="正常" value="正常"></el-option>
            <el-option label="异常" value="异常"></el-option>
            <el-option label="维修中" value="维修中"></el-option>
            <el-option label="已更换" value="已更换"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitEditForm">确定</el-button>
          <el-button @click="editDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


    <!-- 新增对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增井盖信息"
      width="60%"
      destroy-on-close
    >
      <el-form 
        :model="addForm" 
        :rules="rules" 
        ref="addFormRef" 
        label-width="120px"
      >
        <el-form-item label="井盖ID" prop="coverId">
          <el-input v-model="addForm.coverId" placeholder="例如: JG000001"></el-input>
        </el-form-item>
        <el-form-item label="位置ID" prop="locationId">
          <el-input v-model.number="addForm.locationId" type="number" placeholder="请输入位置ID"></el-input>
        </el-form-item>
        <el-form-item label="是否存在" prop="coverExists">
          <el-radio-group v-model="addForm.coverExists">
            <el-radio :label="true">存在</el-radio>
            <el-radio :label="false">不存在</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否损坏" prop="coverDamaged">
          <el-radio-group v-model="addForm.coverDamaged">
            <el-radio :label="true">损坏</el-radio>
            <el-radio :label="false">未损坏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="addForm.status" placeholder="请选择状态">
            <el-option label="正常" value="正常"></el-option>
            <el-option label="异常" value="异常"></el-option>
            <el-option label="维修中" value="维修中"></el-option>
            <el-option label="已更换" value="已更换"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAddForm">提交</el-button>
          <el-button @click="addDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


    <!-- 数据操作区和表格部分 -->
    <el-row>
      <el-row :gutter="10" style="width: 100%; margin-bottom: 20px; align-items: center;">
        <el-col :span="6">
          <el-input 
            placeholder="输入井盖ID进行查询" 
            v-model="searchCoverId" 
            style="width: 100%;"
            @keyup.enter="handleSearch"
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-select 
            v-model="searchStatus" 
            placeholder="按状态筛选" 
            style="width: 100%;"
          >
            <el-option label="全部状态" value=""></el-option>
            <el-option label="正常" value="正常"></el-option>
            <el-option label="异常" value="异常"></el-option>
            <el-option label="维修中" value="维修中"></el-option>
            <el-option label="已更换" value="已更换"></el-option>
          </el-select>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="primary" 
            @click="handleSearch" 
            style="width: 100%;"
          >
            <i class="el-icon-search"></i> 搜索
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="success" 
            @click="resetSearch" 
            style="width: 100%;"
          >
            <i class="el-icon-refresh"></i> 重置
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="primary" 
            @click="openAddDialog" 
            style="width: 100%;"
          >
            <i class="el-icon-plus"></i> 新增
          </el-button>
        </el-col>
      </el-row>
      
      <!-- 表格部分 -->
      <el-table 
        :data="filteredData.slice((currentPage-1)*pageSize, currentPage*pageSize)" 
        border 
        style="width: 100%;"
        height="450"
      >
        <el-table-column prop="coverId" label="井盖ID" width="100" align="center"></el-table-column>
        <el-table-column prop="locationId" label="位置ID" width="120" align="center"></el-table-column>
        <el-table-column prop="coverExists" label="是否存在" width="120" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.coverExists ? 'success' : 'danger'">
              {{ scope.row.coverExists ? '存在' : '不存在' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="coverDamaged" label="是否损坏" width="120" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.coverDamaged ? 'danger' : 'success'">
              {{ scope.row.coverDamaged ? '损坏' : '未损坏' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="140" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button type="primary" size="mini" @click="openDetailDialog(scope.row)">
                <i class="el-icon-view"></i> 查看
              </el-button>
              <el-button type="warning" size="mini" @click="openEditDialog(scope.row)">
                <i class="el-icon-edit"></i> 编辑
              </el-button>
              <el-button type="danger" size="mini" @click="deleteManholeCover(scope.row)">
                <i class="el-icon-delete"></i> 删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <el-row type="flex" justify="center" style="margin-top: 20px;">
        <el-pagination 
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5,10,20,50]" 
          :page-size="pageSize" 
          :total="filteredData.length"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </el-row>
    </el-row>
  </div>
</template>


<script setup>
import { ref, reactive, onMounted } from 'vue'
import { post } from '../../utils/axios.js'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'


// 对话框状态
const dialogVisible = ref(false)
const editDialogVisible = ref(false)
const addDialogVisible = ref(false)


// 搜索条件
const searchCoverId = ref('')
const searchStatus = ref('')


// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)


// 数据存储
const manholeCoversList = ref([])
const filteredData = ref([])


// 表单引用
const editFormRef = ref(null)
const addFormRef = ref(null)


// 当前选中的井盖信息
const currentManholeCover = reactive({
  coverId: null,
  locationId: null,
  coverExists: null,
  coverDamaged: null,
  status: ''
})


// 编辑表单数据
const editForm = reactive({
  coverId: null,
  locationId: null,
  coverExists: null,
  coverDamaged: null,
  status: ''
})


// 新增表单数据
const addForm = reactive({
  coverId: '',
  locationId: null,
  coverExists: true,
  coverDamaged: false,
  status: ''
})


// 表单验证规则
const rules = reactive({
  coverId: [
    { required: true, message: '请输入井盖ID', trigger: 'blur' }
  ],
  locationId: [
    { required: true, message: '请输入位置ID', trigger: 'blur' },
    { type: 'number', message: '位置ID必须为数字', trigger: 'blur' }
  ],
  coverExists: [
    { required: true, message: '请选择是否存在', trigger: 'change' }
  ],
  coverDamaged: [
    { required: true, message: '请选择是否损坏', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
})


// 根据状态获取标签样式
const getStatusTagType = (status) => {
  switch(status) {
    case '正常': return 'success'
    case '异常': return 'warning'
    case '维修中': return 'info'
    case '已更换': return 'primary'
    default: return ''
  }
}


// 打开详情对话框
function openDetailDialog(row) {
  dialogVisible.value = true
  Object.assign(currentManholeCover, row)
}


// 打开编辑对话框
function openEditDialog(row) {
  editDialogVisible.value = true
  Object.assign(editForm, {
    coverId: row.coverId,
    locationId: row.locationId,
    coverExists: row.coverExists,
    coverDamaged: row.coverDamaged,
    status: row.status
  })
}


// 打开新增对话框
function openAddDialog() {
  addDialogVisible.value = true
  if (addFormRef.value) {
    addFormRef.value.resetFields()
  }
  // 重置表单默认值
  addForm.coverId = ''
  addForm.locationId = null
  addForm.coverExists = true
  addForm.coverDamaged = false
  addForm.status = ''
}


// 提交编辑表单
function submitEditForm() {
  editFormRef.value.validate((valid) => {
    if (!valid) return;
    
    const loading = ElLoading.service({ text: '更新中...' })
    post('/sc/manholecover/updateById', editForm, (res) => {
      loading.close()
      if (res.status === 1 || res.includes('成功')) {
        ElMessage.success('更新成功！')
        editDialogVisible.value = false
        fetchManholeCoversList()
      } else {
        ElMessage.error(res.msg || '更新失败')
      }
    })
  })
}


// 提交新增表单
function submitAddForm() {
  addFormRef.value.validate((valid) => {
    if (!valid) return;
    
    const loading = ElLoading.service({ text: '添加中...' })
    post('/sc/manholecover/add', addForm, (res) => {
      loading.close()
      if (res.status === 1 || res.includes('成功')) {
        ElMessage.success('添加成功！')
        addDialogVisible.value = false
        fetchManholeCoversList()
      } else {
        ElMessage.error(res.msg || '添加失败')
      }
    })
  })
}


// 删除井盖信息
function deleteManholeCover(row) {
  ElMessageBox.confirm(`确定删除井盖信息 ${row.coverId} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const loading = ElLoading.service({ text: '删除中...' })
    post('/sc/manholecover/deleteById', { coverId: row.coverId }, (res) => {
      loading.close()
      if (res.status === 1 || res.includes('成功')) {
        ElMessage.success('删除成功！')
        fetchManholeCoversList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    })
  }).catch(() => {})
}


// 搜索处理
function handleSearch() {
  const loading = ElLoading.service({ text: '搜索中...' })
  
  if (searchStatus.value) {
    // 按状态搜索，调用后端接口
    post('/sc/manholecover/byStatus', { status: searchStatus.value }, (res) => {
      loading.close()
      if (res && res.data) {
        filteredData.value = res.data
      } else if (Array.isArray(res)) {
        filteredData.value = res
      } else {
        filteredData.value = []
      }
      
      showSearchResultMessage()
    })
  } else if (searchCoverId.value) {
    // 按井盖ID搜索，本地过滤
    filteredData.value = manholeCoversList.value.filter(item => 
      item.coverId.includes(searchCoverId.value)
    )
    loading.close()
    showSearchResultMessage()
  } else {
    // 显示全部
    filteredData.value = [...manholeCoversList.value]
    loading.close()
    showSearchResultMessage()
  }
  
  currentPage.value = 1 // 重置到第一页
}


// 显示搜索结果消息
function showSearchResultMessage() {
  if (filteredData.value.length > 0) {
    ElMessage.success(`找到 ${filteredData.value.length} 条记录`)
  } else {
    ElMessage.warning('未找到匹配记录')
  }
}


// 重置搜索
function resetSearch() {
  searchCoverId.value = ''
  searchStatus.value = ''
  filteredData.value = [...manholeCoversList.value]
  currentPage.value = 1
}


// 分页大小变化
function handleSizeChange(val) {
  pageSize.value = val
  currentPage.value = 1
}


// 当前页变化
function handleCurrentChange(val) {
  currentPage.value = val
}


// 获取所有井盖信息
function fetchManholeCoversList() {
  const loading = ElLoading.service({ text: '加载中...' })
  post('/sc/manholecover/getAll', {}, (res) => {
    loading.close()
    if (res.status === 1 && res.data) {
      manholeCoversList.value = res.data
      filteredData.value = [...res.data]
    } else {
      ElMessage.error(res.msg || '获取数据失败')
      manholeCoversList.value = []
      filteredData.value = []
    }
  })
}


// 页面加载时获取数据
onMounted(() => {
  fetchManholeCoversList()
})
</script>


<style scoped>
.manhole-covers-container {
  width: auto;
  padding: 20px;
}
/* 标题样式 */
.page-header {
  padding: 10px 0;
  border-bottom: 1px solid #e5e7eb;
}

.title-wrapper {
  display: inline-flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.main-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.sub-title {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.el-icon--large {
  font-size: 28px;
  color: #409eff;
}

.operation-buttons {
  display: flex;
  gap: 4px;
}


.operation-buttons .el-button--mini {
  padding: 1px 6px;
  font-size: 12px;
  height: 24px;
  min-width: auto;
}



.el-table {
  margin-top: 20px;
}


.el-pagination {
  margin-top: 20px;
}


.el-form-item .el-button,
.el-col .el-button {
  margin-right: 5px;
}


.el-form {
  padding: 10px;
}
</style>
